import logging

from pylons import request, response, session
from pylons import tmpl_context as c
from pylons.controllers.util import abort, redirect_to

from ajaxblog.lib.base import BaseController, render
from ajaxblog.model import Post
from ajaxblog.model.meta import Session as S
from sqlalchemy import desc
from formalchemy import FieldSet

log = logging.getLogger(__name__)

class BlogController(BaseController):

    def index(self):
        fs = FieldSet(Post)
        fs.configure(include=[fs.title, fs.body.textarea()])
        if request.method == 'POST':
            fs.rebind(data=request.params)
            if fs.validate():
                fs.sync()
                S.commit()
        fs.rebind(data=None) # clear form
        c.posts = S.query(Post).order_by(desc(Post.posted_at)).all()
        c.fs = fs
        return render('/index.mako')
    
